import { createWebHistory, createRouter } from 'vue-router'
import Index from '../views/Index.vue'
import _404 from '../views/404.vue'
import HomePage from '../components/HomePage.vue'
import Goods from '../components/Goods.vue'
import User from '../components/User.vue'
import Login from '../views/Login.vue'
import Category from '../components/Category.vue'
import { useTokenStore } from '../store/tokenStore'
import { onMounted } from 'vue'


const Router = createRouter({
    history: createWebHistory(),
    routes: [{
            path: '/',
            redirect: '/login'
        }, {
            path: '/login',
            component: Login
        }, {
            path: '/index',
            component: Index,
            redirect: '/index/homepage',

            children: [{
                path: 'homepage',
                component: HomePage
            }, {
                path: 'category',
                component: Category
            }, {
                path: 'goods',
                component: Goods
            }, {
                path: 'user',
                component: User
            }]
        },
        {
            path: '/:pathMatch(.*)*',
            component: _404
        },
    ]
})

// 白名单
const WHITE_LIST = ['/login']

Router.beforeEach((to) => {
    const { path } = to
    // 是白名单
    if (WHITE_LIST.includes(path)) {
        return true;
    }

    const tokenStore = useTokenStore()
    console.log(tokenStore.token);
    
    if (tokenStore.token) {
        return true
    } else {
        // 没有 token 并且不是白名单
        return `/login?redirectUrl=${path}`
    }
})


export default Router